﻿using CefSharp;
using CefSharp.WinForms;
using EDesk.cefwrapper;
using EDesk.apis;
using EDesk.kit;
using System;
using System.IO;
using System.Windows.Forms;

namespace EDesk
{
    public partial class MainForm : Form
    {

        public static MainForm ins;

        private ChromiumWebBrowser browser;

        /// <summary>
        /// 入口函数
        /// </summary>
        public MainForm()
        {
            ins = this;
            var indexUrl = Cfgs.GetIndexUrl();
            InitializeComponent();
            InitializeChromium(indexUrl);
        }

        //初始化浏览器并启动
        public void InitializeChromium(String indexUrl)
        {
            //不检测跨线程修改窗体UI
            Control.CheckForIllegalCrossThreadCalls = false;

            //退出清理
            CefSharpSettings.SubprocessExitIfParentProcessClosed = true;
            CefSharpSettings.ShutdownOnExit = true;

            //支持高DPI
            Cef.EnableHighDPISupport();

            //初始化缓存目录
            var cachePath = Path.GetFullPath("runcache");
            if (!Directory.Exists(cachePath))
            {
                Directory.CreateDirectory(cachePath);
            }

            //参数设置
            CefSettings settings = new CefSettings
            {
                UserAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 EDesk/1.0.0"
            };
            //禁止GPU(图形处理器) 加速
            settings.CefCommandLineArgs.Add("disable-gpu", "1");
            //支持媒体流    
            settings.CefCommandLineArgs.Add("enable-media-stream", "1");
            //不使用代理服务器
            settings.CefCommandLineArgs.Add("no-proxy-server", "1");
            //默认语言
            settings.Locale = "zh-CN";
            //引擎语言
            settings.AcceptLanguageList = "zh-CN,zh;q=0.8";
            //保存会话
            settings.PersistSessionCookies = true;
            //缓存位置
            settings.CachePath = cachePath;
            //关闭同源策略,允许跨域
            settings.CefCommandLineArgs.Add("--disable-web-security", "1");
            //忽略证书错误
            settings.IgnoreCertificateErrors = true;
            settings.CefCommandLineArgs.Add("--ignore-urlfetcher-cert-requests", "1");
            settings.CefCommandLineArgs.Add("--ignore-certificate-errors", "1");

            //加载参数配置
            Cef.Initialize(settings);

            //创建实例
            browser = new ChromiumWebBrowser(indexUrl)
            {
                //重写弹窗
                LifeSpanHandler = new LifeSpanHandler(),
                //重写右键
                MenuHandler = new MenuHandler(),
                //重写键盘事件
                KeyboardHandler = new KeyBoardHander(),
                //重写页面事件
                DisplayHandler = new DisplayHandler(),
                //重写弹窗
                JsDialogHandler = new JsDialogHandler(),
                //重写浏览器渲染相关
                RenderProcessMessageHandler = new RenderProcessMessageHandler(),
                //布局
                Dock = DockStyle.Fill
            };

            //注入JS回调对象
            browser.JavascriptObjectRepository.Register("EDesk", new JsApi(), isAsync: true, options: BindingOptions.DefaultBinder);
            //chromeBrowser.JavascriptObjectRepository.ObjectBoundInJavascript += (mysender, mye) =>
            //{
            //    var objName = mye.ObjectName;
            //    Console.WriteLine($"内置JS对象“{objName}”已经注入完成。");
            //};

            //添加控件
            this.Controls.Add(browser);
        }

        /// <summary>
        /// 退出程序时销毁对象
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Main_Closed(object sender, EventArgs e)
        {
            browser.Dispose();
            browser = null;
            Cef.Shutdown();
        }

    }
}
